package cn.db.iot.service.impl;

import cn.db.iot.entity.SysUser;
import cn.db.iot.mapper.SysUserMapper;
import cn.db.iot.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 系统用户服务实现类
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    
    @Override
    public SysUser getByUsername(String username) {
        if (username == null || username.trim().isEmpty()) {
            return null;
        }
        
        // 使用MyBatis Plus的查询方法
        return this.lambdaQuery()
                .eq(SysUser::getName, username.trim())
                .eq(SysUser::getDelFlag, 0) // 只查询未删除的用户
                .one();
    }
    
    @Override
    public void exportToExcel(List<SysUser> users, HttpServletResponse response) throws IOException {
        // TODO: 实现Excel导出功能
        // 这里可以使用POI或EasyExcel库来实现Excel导出
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=users.xlsx");
        
        // 简单的CSV格式导出作为示例
        StringBuilder csv = new StringBuilder();
        csv.append("ID,用户名,真实姓名,邮箱,手机号,状态,创建时间\n");
        
        for (SysUser user : users) {
            csv.append(String.format("%d,%s,%s,%s,%s,%s,%s\n",
                    user.getId(),
                    user.getName(),
                    user.getRealName(),
                    user.getEmail(),
                    user.getMobile(),
                    user.getStatus() == 1 ? "正常" : "禁用",
                    user.getCreateTime()
            ));
        }
        
        response.getWriter().write(csv.toString());
    }
}
